package com.epoint.netty.rpc.client;

import com.epoint.netty.chat.protocol.MessageCodecSharable;
import com.epoint.netty.protocol.self.Message;
import com.epoint.netty.protocol.self.MessageCodec;
import com.epoint.netty.rpc.common.RpcRequestMessage;
import com.epoint.netty.rpc.server.User;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class Client_V1 {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        MessageCodecSharable messageCodecSharable = new MessageCodecSharable();
        ChannelFuture connect = new Bootstrap()
                .group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(messageCodecSharable);
                    }
                })
                .connect("localhost", 8080);

        connect.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                // 客户端 成功连接服务器的回调函数
                RpcRequestMessage mesg = new RpcRequestMessage(1, "com.epoint.netty.rpc.server.UserService",
                        "getUserByName", User.class, new Class[]{String.class}, new Object[]{"纪宽豪"});
                channelFuture.channel().writeAndFlush(mesg);
            }
        });

        // 配置关闭事件
        ChannelFuture channelFuture = connect.channel().closeFuture();
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            eventExecutors.shutdownGracefully();
        });

    }
}
